package com.fjnu.service.impl;

import com.fjnu.dao.ArticleDao;
import com.fjnu.dao.UserDao;
import com.fjnu.dto.ArticleConditionDto;
import com.fjnu.entity.Article;
import com.fjnu.entity.User;
import com.fjnu.service.ArticleService;
import com.fjnu.vo.ArticleUpdateDto;
import com.fjnu.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private UserDao userDao;
    @Override
    public PageResult<Article> queryByArticleCondition(ArticleConditionDto articleCond, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) pageNum = 1;
        if (pageSize == null || pageSize < 1) pageSize = 10;

        List<Article> allArticles = new ArrayList<>();
        if (articleCond.getUserId() != null) {
            List<Article> userArticles = articleDao.selectByUserId(articleCond.getUserId());
            if (userArticles != null) allArticles.addAll(userArticles);
        } else if (articleCond.getTitle() != null) {
            List<Article> keywordArticles = articleDao.selectByKeyWord(articleCond.getTitle());
            if (keywordArticles != null) allArticles.addAll(keywordArticles);
        } else if (articleCond.getCategoryId() != null) {
            List<Article> categoryArticles = articleDao.selectByCategory(articleCond.getCategoryId());
            if (categoryArticles != null) allArticles.addAll(categoryArticles);
        }
        // 内存分页
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allArticles.size());

        if (startIndex >= allArticles.size()) {
            return new PageResult<>(pageNum, pageSize, (long) allArticles.size(), null);
        }
        List<Article> pageData = allArticles.subList(startIndex, endIndex);
        return new PageResult<>(pageNum, pageSize, (long) allArticles.size(), pageData);
    }

    @Override
    public Article queryById(String articleId) {
        if (articleId == null || articleId.trim().isEmpty()) {
            return null;
        }

        try {
            Integer id = Integer.parseInt(articleId);

            // 临时方案：通过时间区间查询所有文章，然后过滤
            List<Article> allArticles = articleDao.selectByTimePeriod(null, null);
            if (allArticles != null) {
                return allArticles.stream()
                        .filter(article -> id.equals(article.getId()))
                        .findFirst()
                        .orElse(null);
            }
            return null;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public Article insertArticle(Article article) {
        if (article == null) return null;

        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setStatus(0); // 默认草稿状态

        // 使用新的方法插入并返回ID
        return articleDao.insertAndReturnId(article);
    }

    @Override
    @Transactional
    public int publishArticle(String articleId, String userId) {
        if (articleId == null || userId == null) return 0;

        try {
            // 1. 更新文章状态为发布(1)
            Integer articleIdInt = Integer.parseInt(articleId);
            Integer userIdInt = Integer.parseInt(userId);

            int updateResult = articleDao.updateStatus(articleIdInt, 1);
            if (updateResult == 0) return 0;

            // 2. 更新用户积分（发布文章+10分）
            int scoreResult = userDao.updateScore(userIdInt, 10L);
            if (scoreResult == 0) return 0;

            return 1;
        } catch (Exception e) {
            throw new RuntimeException("发布文章失败", e);
        }
    }

    @Override
    @Transactional
    public int publishArticlesByBatch(String[] articleIds, String userId) {
        if (articleIds == null || articleIds.length == 0 || userId == null) return 0;

        try {
            Integer userIdInt = Integer.parseInt(userId);
            List<Integer> articleIdList = new ArrayList<>();

            for (String articleId : articleIds) {
                articleIdList.add(Integer.parseInt(articleId));
            }

            // 1. 批量更新文章状态
            int updateResult = articleDao.batchUpdateStatus(articleIdList, 1);
            if (updateResult == 0) return 0;

            // 2. 更新用户积分（每篇文章+10分）
            long totalScore = articleIds.length * 10L;
            int scoreResult = userDao.updateScore(userIdInt, totalScore);
            if (scoreResult == 0) return 0;

            return 1;
        } catch (Exception e) {
            throw new RuntimeException("批量发布文章失败", e);
        }
    }

    @Override
    @Transactional
    public int updateArticle(ArticleUpdateDto articleUpdateDto) {
        if (articleUpdateDto == null || articleUpdateDto.getArticleId() == null) return 0;

        try {
            Integer articleId = Integer.parseInt(articleUpdateDto.getArticleId());
            ArticleConditionDto condition = new ArticleConditionDto();

            if (articleUpdateDto.getTitle() != null) {
                condition.setTitle(articleUpdateDto.getTitle());
            }
            if (articleUpdateDto.getContent() != null) {
                condition.setContent(articleUpdateDto.getContent());
            }
            if (articleUpdateDto.getStatus() != null) {
                condition.setStatus(articleUpdateDto.getStatus());
            }
            if (articleUpdateDto.getDescription() != null) {
                condition.setDescription(articleUpdateDto.getDescription());
            }
            if (articleUpdateDto.getCategoryId() != null) {
                condition.setCategoryId(articleUpdateDto.getCategoryId());
            }

            return articleDao.updateByCondition(articleId, condition);
        } catch (Exception e) {
            throw new RuntimeException("更新文章失败", e);
        }
    }

    @Override
    @Transactional
    public int removeArticle(String articleId, String userId) {
        if (articleId == null || userId == null) return 0;

        try {
            Integer articleIdInt = Integer.parseInt(articleId);
            Integer userIdInt = Integer.parseInt(userId);

            // 1. 删除文章
            int deleteResult = articleDao.deleteById(articleIdInt);
            if (deleteResult == 0) return 0;

            // 2. 更新用户积分（删除文章-5分）
            int scoreResult = userDao.updateScore(userIdInt, -5L);
            if (scoreResult == 0) return 0;

            return 1;
        } catch (Exception e) {
            throw new RuntimeException("删除文章失败", e);
        }
    }
}